#include "filesys/inode.h"
#include <list.h>
#include <debug.h>
#include <round.h>
#include <string.h>
#include "filesys/filesys.h"
#include "filesys/free-map.h"
#include "threads/malloc.h"
#include "threads/thread.h"
// 3 idiots added begin
#include "filesys/cache.h"

#define INODE_MAX_COUNT 406

static int inode_cnt = 0;
// 3 idiots added end

/* Identifies an inode. */
#define INODE_MAGIC 0x494e4f44

/* Returns the number of sectors to allocate for an inode SIZE
   bytes long. */
static inline size_t
bytes_to_sectors (off_t size)
{
  return DIV_ROUND_UP (size, DISK_SECTOR_SIZE);
}

/* Returns the disk sector that contains byte offset POS within
   INODE.
   Returns -1 if INODE does not contain data for a byte at offset
   POS. */
static disk_sector_t byte_to_sector (const struct inode *inode, off_t pos) 
{
   // 3 idiots added begin
   ASSERT (inode != NULL);
   disk_sector_t disk_sector = -1;

   if (pos < inode_length(inode))
   {        
	off_t ofs = pos / DISK_SECTOR_SIZE;

	struct inode_disk* id = inode_create_disk (inode->sector);

	if (ofs < DIRECT_DISK_SECTOR_SIZE)
	{
	   disk_sector = id->dir_disk_sector_list[ofs];
	}
	else if (ofs < DIR_INDIR_DISK_SECTOR_SIZE)
	{
           inode_read_or_write (id->indir_disk_sector, (void *) &disk_sector, ofs - DIRECT_DISK_SECTOR_SIZE, true);
	}
	else if (ofs < ALL_LINKED_DISK_SECTOR_SIZE)
	{
	   unsigned temp_num = ofs - (DIR_INDIR_DISK_SECTOR_SIZE);
           inode_read_or_write (id->squared_indir_disk_sector, (void *) &disk_sector, 
                                temp_num / INDIRECT_DISK_SECTOR_SIZE, true);
           inode_read_or_write (disk_sector, (void *) &disk_sector, temp_num % DIRECT_DISK_SECTOR_SIZE, true);
	}
        free (id);
    }

    return disk_sector;
    // 3 idiots added end
}

/* List of open inodes, so that opening a single inode twice
   returns the same `struct inode'. */
static struct list open_inodes;

/* Initializes the inode module. */
void
inode_init (void) 
{
  // 3 idiots added begin
  inode_cnt = 0;
  // 3 idiots added end
  list_init (&open_inodes);
}

/* Initializes an inode with LENGTH bytes of data and
   writes the new inode to sector SECTOR on the file system
   disk.
   Returns true if successful.
   Returns false if memory or disk allocation fails. */
bool inode_create (disk_sector_t sector, off_t length, bool arg_is_dir)
{
   struct inode_disk *disk_inode = NULL;
   bool success = false;

   ASSERT (length >= 0);
   ASSERT (sizeof *disk_inode == DISK_SECTOR_SIZE);

   // 3 idiots added begin
   if (inode_cnt > INODE_MAX_COUNT)
   {
      return false;
   }
   // 3 idiots added end

   disk_inode = calloc (1, sizeof *disk_inode);

   if (disk_inode != NULL)
   {
      // 3 idiots added begin
      inode_initialize_disk_inode (disk_inode, sector, length, arg_is_dir);
      success = true;
      // 3 idiots added begin
   }
   inode_cnt++;
   return success;
}

/* Reads an inode from SECTOR
   and returns a `struct inode' which contains it.
   Returns a null pointer if memory allocation fails. */
struct inode *
inode_open (disk_sector_t sector) 
{
  struct list_elem *e;
  struct inode *inode;

  /* Check whether this inode is already open. */
  for (e = list_begin (&open_inodes); e != list_end (&open_inodes);
       e = list_next (e)) 
    {
      inode = list_entry (e, struct inode, elem);
      if (inode->sector == sector) 
        {
          inode_reopen (inode);
          return inode; 
        }
    }

  /* Allocate memory. */
  inode = malloc (sizeof *inode);
  if (inode == NULL)
    return NULL;

  /* Initialize. */
  list_push_front (&open_inodes, &inode->elem);
  inode->sector = sector;
  inode->open_cnt = 1;
  inode->deny_write_cnt = 0;
  inode->removed = false;

  return inode;
}

/* Reopens and returns INODE. */
struct inode *
inode_reopen (struct inode *inode)
{
  if (inode != NULL)
  {
    inode->open_cnt++;
  }
  return inode;
}

/* Returns INODE's inode number. */
disk_sector_t
inode_get_inumber (const struct inode *inode)
{
  return inode->sector;
}

/* Closes INODE and writes it to disk.
   If this was the last reference to INODE, frees its memory.
   If INODE was also a removed inode, frees its blocks. */
void
inode_close (struct inode *inode) 
{
    /* Ignore null pointer. */
    if (inode == NULL)
      return;

    /* Release resources if this was the last opener. */
    if (--inode->open_cnt == 0)
    {
       // 3 idiots added begin
       lock_acquire (&thread_current ()->id_lock);
       // 3 idiots added end

       /* Remove from inode list and release lock. */
       list_remove (&inode->elem);

       /* Deallocate blocks if removed. */
       if (inode->removed)
       {
           // 3 idiots added begin
	   inode_make_empty (inode);
           inode_cnt--;
           // 3 idiots added end
	   free_map_release (inode->sector, 1);
        }

        // 3 idiots added begin
        lock_release (&thread_current ()->id_lock);
        // 3 idiots added end
	free (inode);
     }
}

/* Marks INODE to be deleted when it is closed by the last caller who
   has it open. */
void
inode_remove (struct inode *inode) 
{
  ASSERT (inode != NULL);
  inode->removed = true;
}

/* Reads SIZE bytes from INODE into BUFFER, starting at position OFFSET.
   Returns the number of bytes actually read, which may be less
   than SIZE if an error occurs or end of file is reached. */
off_t inode_read_at (struct inode *inode, void *buffer_, off_t size, off_t offset) 
{
  void *buffer = buffer_;
  off_t bytes_read = 0;

  while (size > 0)
  {
      /* Disk sector to read, starting byte offset within sector. */
      disk_sector_t sector_idx = byte_to_sector (inode, offset);

      disk_sector_t invalid_idx = (disk_sector_t) -1;

      if (sector_idx != invalid_idx)
      {
         int sector_ofs = offset % DISK_SECTOR_SIZE;

	 /* Bytes left in inode, bytes left in sector, lesser of the two. */
	 off_t inode_left = inode_length (inode) - offset;
         int sector_left = DISK_SECTOR_SIZE - sector_ofs;
	 int min_left = inode_left < sector_left ? inode_left : sector_left;

	 /* Number of bytes to actually copy out of this sector. */
	 int chunk_size = size < min_left ? size : min_left;
	 if (chunk_size <= 0)
	    break;
         
         // 3 idiots added begin
	 cache_read_sector (sector_idx, buffer + bytes_read, sector_ofs, chunk_size);
         // 3 idiots added end

	 /* Advance. */
	 size -= chunk_size;
	 offset += chunk_size;
	 bytes_read += chunk_size;
      }
      else
      {
	break;
      }
  }
  return bytes_read;
}

/* Writes SIZE bytes from BUFFER into INODE, starting at OFFSET.
   Returns the number of bytes actually written, which may be
   less than SIZE if end of file is reached or an error occurs.
   (Normally a write at end of file would extend the inode, but
   growth is not yet implemented) */
off_t inode_write_at (struct inode *inode, const void *buffer_, off_t size, off_t offset) 
{
    const void *buffer = buffer_;
    off_t bytes_written = 0;

    if (inode->deny_write_cnt > 0)
    {
	return 0;
    }

    // 3 idiots added begin
    off_t bytes_in_inode = inode_length (inode);

    if (offset + size > bytes_in_inode)
    {
	inode_grow (inode, offset + size - bytes_in_inode);
	bytes_in_inode += offset + size;
    }
    // 3 idiots added end

    while (size > 0)
    {
	 /* Sector to write, starting byte offset within sector. */
	 disk_sector_t sector_idx = byte_to_sector (inode, offset);
	 if (sector_idx == (unsigned)-1)
	 {
	     break;
	 }
	 int sector_ofs = offset % DISK_SECTOR_SIZE;

	 /* Bytes left in inode, bytes left in sector, lesser of the two. */
	 off_t inode_left = bytes_in_inode - offset;
	 int sector_left = DISK_SECTOR_SIZE - sector_ofs;
	 int min_left = inode_left < sector_left ? inode_left : sector_left;

	 /* Number of bytes to actually write into this sector. */
	 int chunk_size = size < min_left ? size : min_left;
	 if (chunk_size <= 0)
         {
	     break;
         }

	 // 3 idiots added begin
	 cache_write_sector (sector_idx, (void*)(buffer + bytes_written), sector_ofs, chunk_size);
         // 3 idiots added end

	 /* Advance. */
	 size -= chunk_size;
	 offset += chunk_size;
	 bytes_written += chunk_size;
     }

     return bytes_written;
}

/* Disables writes to INODE.
   May be called at most once per inode opener. */
void
inode_deny_write (struct inode *inode) 
{
  inode->deny_write_cnt++;
  ASSERT (inode->deny_write_cnt <= inode->open_cnt);
}

/* Re-enables writes to INODE.
   This must be called once by each inode opener who has called
   inode_deny_write() on the inode, before closing the inode. */
void
inode_allow_write (struct inode *inode) 
{
  ASSERT (inode->deny_write_cnt > 0);
  ASSERT (inode->deny_write_cnt <= inode->open_cnt);
  inode->deny_write_cnt--;
}

// 3 idiots added begin
bool inode_is_dir (const struct inode* inode)
{
  enum inode_type temp_type = INODE_FILE;
  cache_read_sector (inode->sector, &temp_type, 0, sizeof(enum inode_type));

  if (temp_type == INODE_FILE)  
  { 
     return false;
  }
  else 
  {  
     return true;
  }
}

/* Returns the length, in bytes, of INODE's data. */
off_t inode_length (const struct inode *inode)
{
  off_t file_length;
  cache_read_sector (inode->sector, (void *)(&file_length), 4, sizeof(off_t));
  return file_length;
}

bool inode_grow (struct inode* inode, off_t len_want_to_grow)
{
  lock_acquire (&thread_current ()->id_lock);

  struct inode_disk* id = inode_create_disk (inode->sector);

  off_t left_bytes = id->id_sec_cnt * DISK_SECTOR_SIZE - id->id_length;
  size_t sectors = bytes_to_sectors (len_want_to_grow - left_bytes);

  unsigned i = 0;
  disk_sector_t temp_disk_sector;

  for (; i < sectors; i++)
  {
     if (free_map_allocate (1, &temp_disk_sector))
     {
	inode_new_sector (inode, temp_disk_sector);
     }
     else
     {
        // Cannot grow
        return false;
     }
   }

   id->id_length += len_want_to_grow;
   cache_write_sector (inode->sector, (void *) &id->id_length, 4, 4);

   lock_release (&thread_current ()->id_lock);
   free (id);
   return true;
}

// Add new sector
void inode_new_sector (struct inode* inode, disk_sector_t disk_sector)
{
   struct inode_disk* id = inode_create_disk (inode->sector);

   if (id->id_sec_cnt < DIRECT_DISK_SECTOR_SIZE)
   {
      id->dir_disk_sector_list[id->id_sec_cnt] = disk_sector;
   }
   else if (id->id_sec_cnt < DIR_INDIR_DISK_SECTOR_SIZE)
   {
       if (id->id_sec_cnt - DIRECT_DISK_SECTOR_SIZE == 0)
       {
	  void* empty_sector = malloc (DISK_SECTOR_SIZE);

	  disk_sector_t indirect_disk_sector;
	  free_map_allocate (1, &indirect_disk_sector);

	  id->indir_disk_sector = indirect_disk_sector;
          inode_read_or_write_empty (indirect_disk_sector, (void *) empty_sector, false);
        }
        inode_read_or_write (id->indir_disk_sector, (void *) &disk_sector, id->id_sec_cnt - DIRECT_DISK_SECTOR_SIZE, false);
    }
    else if (id->id_sec_cnt < ALL_LINKED_DISK_SECTOR_SIZE)
    {
	off_t num = id->id_sec_cnt - (DIR_INDIR_DISK_SECTOR_SIZE);
        off_t ofs_indir = num % INDIRECT_DISK_SECTOR_SIZE;
	off_t ofs_squared_indir = num / INDIRECT_DISK_SECTOR_SIZE;

	if (num == 0)
	{
	   void* empty_sector = malloc (DISK_SECTOR_SIZE);

	   disk_sector_t dindir_disk_sector;
	   free_map_allocate (1, &dindir_disk_sector);

	   id->squared_indir_disk_sector = dindir_disk_sector;
           inode_read_or_write_empty (dindir_disk_sector, (void *) empty_sector, false);
	 }
	 if (ofs_indir == 0)
	 {
            void* empty_sector = malloc (DISK_SECTOR_SIZE);

	    disk_sector_t indirect_disk_sector;
	    free_map_allocate (1, &indirect_disk_sector);

	    id->indir_disk_sector = indirect_disk_sector;
            inode_read_or_write_empty (indirect_disk_sector, (void *) empty_sector, false);
            inode_read_or_write (id->squared_indir_disk_sector, (void *) &indirect_disk_sector, ofs_squared_indir, false);
	 }

	 disk_sector_t indir_disk_sector;
         inode_read_or_write (id->squared_indir_disk_sector, (void *) &indir_disk_sector, ofs_squared_indir, true);
         inode_read_or_write (indir_disk_sector, (void *) &disk_sector, ofs_indir, false);
      }

      id->id_sec_cnt++;
      inode_read_or_write_empty (inode->sector, (void *) id, false);

      free(id);
}

static void inode_release_disk_sectors (struct inode_disk* arg_id)
{
    unsigned i = 0;
    for (; i < arg_id->id_sec_cnt; i++)
    {
	free_map_release (arg_id->dir_disk_sector_list[i], 1);
    }
}

static void inode_release_indirect_disk_sector (struct indir_disk_sector* arg_in_ds, unsigned arg_num)
{
    unsigned i = 0;
    for (; i < arg_num; i++)
    {
        free_map_release (arg_in_ds->dir_disk_sector_list[i], 1);
    }
}

struct indir_disk_sector* inode_create_indir_disk_sector (disk_sector_t arg_src)
{
    struct indir_disk_sector* temp_indir_disk_sector = malloc (DISK_SECTOR_SIZE);
    inode_read_or_write_empty (arg_src, (void *) temp_indir_disk_sector, true);
    return temp_indir_disk_sector;
}

struct inode_disk* inode_create_disk (disk_sector_t arg_src)
{
   struct inode_disk* temp_id = malloc (DISK_SECTOR_SIZE);
   //if(temp_id==NULL)
   //    return NULL;
   inode_read_or_write_empty (arg_src, (void *) temp_id, true);
   return temp_id;
}

void inode_make_empty (struct inode* inode)
{
   struct inode_disk* id = inode_create_disk (inode->sector);

   // sector left > 0
   if (id->id_sec_cnt > 0)
   {
	 if (id->id_sec_cnt > DIR_INDIR_DISK_SECTOR_SIZE)
	 {
            struct indir_disk_sector* squared_indir_sector = inode_create_indir_disk_sector (id->squared_indir_disk_sector);

	    unsigned di_length = id->id_sec_cnt - (DIR_INDIR_DISK_SECTOR_SIZE);

	    while (di_length > 0)
	    {
		off_t di_offset = di_length / INDIRECT_DISK_SECTOR_SIZE;
                unsigned num = di_length;

                struct indir_disk_sector* indir_disk_sector = 
                               inode_create_indir_disk_sector (squared_indir_sector->dir_disk_sector_list[di_offset]);

		if (num > INDIRECT_DISK_SECTOR_SIZE) 
                { 
                   num = num % INDIRECT_DISK_SECTOR_SIZE; 
                }

                inode_release_indirect_disk_sector (indir_disk_sector, num);
		di_length -= num;
	    }

	    id->id_sec_cnt = DIR_INDIR_DISK_SECTOR_SIZE;
         }

	 if (id->id_sec_cnt > DIRECT_DISK_SECTOR_SIZE)
	 {
	    unsigned num = id->id_sec_cnt - DIRECT_DISK_SECTOR_SIZE;
            struct indir_disk_sector* indir_disk_sector = inode_create_indir_disk_sector (id->indir_disk_sector);

            inode_release_indirect_disk_sector (indir_disk_sector, num);
	 }

         inode_release_disk_sectors (id);
	 id->id_sec_cnt = 0;
	 id->id_length = 0;

         inode_read_or_write_empty (inode->sector, (void *) id, false);
    }
    free (id);
}

void inode_initialize_disk_inode (struct inode_disk* arg_disk_inode, disk_sector_t arg_sec, 
off_t arg_len, bool arg_is_dir)
{
    arg_disk_inode->id_length = 0;
    arg_disk_inode->id_sec_cnt = 0;
    arg_disk_inode->id_magic_num = INODE_MAGIC;
    
    if (arg_is_dir)
    {
       arg_disk_inode->id_type = INODE_DIR;
    }
    else
    {
       arg_disk_inode->id_type = INODE_FILE;
    }

    inode_read_or_write_empty (arg_sec, (void*) arg_disk_inode, false);

    struct inode* temp_inode = inode_open (arg_sec);
    inode_grow (temp_inode, arg_len);
    inode_close (temp_inode);
    free (arg_disk_inode);
}

void inode_read_or_write_empty (disk_sector_t arg_src, void* arg_dest, bool is_read)
{
    if (is_read)
    {
       cache_read_sector (arg_src, arg_dest, 0, DISK_SECTOR_SIZE);
    }
    else
    {
       cache_write_sector (arg_src, arg_dest, 0, DISK_SECTOR_SIZE);
    }
}

void inode_read_or_write (disk_sector_t arg_src, void* arg_dest, off_t arg_ofs, bool is_read)
{
    if (is_read)
    {
       cache_read_sector (arg_src, arg_dest, arg_ofs * sizeof(disk_sector_t), sizeof(disk_sector_t));
    }
    else
    {
       cache_write_sector (arg_src, arg_dest, arg_ofs * sizeof(disk_sector_t), sizeof(disk_sector_t));
    }
}
// 3 idiots added end
